<template>
  <view>
    <u-sticky >
      <u-tag :text="'任务总数：' + total" type="success"></u-tag>
    </u-sticky>
    <u-form :model="param" ref="uQueryForm">
      <u-row>
        <u-col span="4">
          <uni-data-select v-model="formType" placeholder="请选择类型" :localdata="formTypeInfo" />
        </u-col>
        <u-col span="6">
          <u--input
              placeholder="请输入"
              border="surround"
              v-model="param.searchKey"
              clearable
              @change="searchList"
          ></u--input>
        </u-col>
      </u-row>
    </u-form>

    <u-loading-icon :show="loading" text="加载中" textSize="18"></u-loading-icon>

    <u-modal :show="show" :title="title" showCancelButton confirmText="提交" @cancel="cancelForm"
             :showConfirmButton="confirmDisabled" @confirm="submitForm">
      <u--form :model="form" ref="uForm">
        <u-form-item label="编码">
          <u--input
              placeholder="请输入物料编码"
              border="surround"
              readonly
              v-model="form.invCode"
          ></u--input>
        </u-form-item>
        <u-form-item label="批次" v-show="form.isBatch === 1 || form.batchNo !== null">
          <u--input
              placeholder="请输入批次号"
              border="surround"
              clearable
              v-model="form.batchNo"
          ></u--input>
        </u-form-item>
        <u-col span="10">
          <u-form-item label="生产日期" @click="DateShow = true" v-show="form.isEffective === 1 || form.productionDate !== null">
            <u--input
                placeholder="请输入生产日期"
                border="surround"
                clearable
                :disabled="true"
                v-model="form.productionDate"
            ></u--input>
          </u-form-item>
        </u-col>
        <u-form-item label="计划">
          <u--input
              border="surround"
              readonly
              v-model="form.qty"
          ></u--input>
        </u-form-item>
        <u-form-item label="累计">
          <u--input
              border="surround"
              readonly
              v-model="form.inQtySum"
          ></u--input>
        </u-form-item>
        <u-form-item label="提交">
          <u--input
              border="surround"
              clearable
              type="number"
              v-model="form.actQty"
          ></u--input>
        </u-form-item>
        <u-calendar :show="DateShow" :mode="DateMmode" @close="DateShow = false" @confirm="confirmDate"></u-calendar>
      </u--form>
    </u-modal>

    <u-list @scrolltolower="scrollTolower"  @scrollWithAnimation="true" :key="listKey">
      <u-list-item v-for="(item, index) in items" :key="index" class="custom-list-item" >
        <view @click="handleSubmit(item)">
          <u-cell :title="`供应商：${item.suppLierName}`"></u-cell>
          <u-cell :title="`订单号：${item.orderNo}`"></u-cell>
          <u-cell :title="`物料编码：${item.invCode}`"></u-cell>
          <u-cell :title="`物料名称：${item.invName}`"></u-cell>
          <u-cell :title="`物料型号：${item.invSpec ? item.invSpec: ''}`"></u-cell>
          <u-row>
            <u-col span="6">
              <u-cell :title="`仓库：${item.whName}`"></u-cell>
            </u-col>
            <u-col span="12">
              <u-cell :title="`计划数量：${item.qty}`"></u-cell>
            </u-col>
          </u-row>
          <u-row>
            <u-col span="4">
              <u-cell :title="`单位：${item.unitName}`"></u-cell>
            </u-col>
            <u-col span="4">
              <u-cell :title="`累计：${item.inQtySum}`"></u-cell>
            </u-col>
          </u-row>
          <u-cell :title="`参考货位：${item.refLocation ? item.refLocation : ''}`"></u-cell>
          <u-cell :title="`批次号：${item.batchNo ? item.batchNo : ''}`"></u-cell>
          <u-cell :title="`类型：${item.businessName}`"></u-cell>
        </view>
      </u-list-item>
    </u-list>
  </view>
</template>
<script>
import UListItem from "../../../../uview-ui/components/u-list-item/u-list-item.vue";
import UList from "../../../../uview-ui/components/u-list/u-list.vue";
import ULoadingIcon from "../../../../uview-ui/components/u-loading-icon/u-loading-icon.vue";
import UCell from "../../../../uview-ui/components/u-cell/u-cell.vue";
import {commitStockInPDA, stockTaskList} from "@/api/work/wareHourse/stockTask";
import URow from "../../../../uview-ui/components/u-row/u-row.vue";
import UCol from "../../../../uview-ui/components/u-col/u-col.vue";
import UModal from "../../../../uview-ui/components/u-modal/u-modal.vue";
import UInput from "../../../../uview-ui/components/u--input/u--input.vue";
import UForm from "../../../../uview-ui/components/u--form/u--form.vue";
import UFormItem from "../../../../uview-ui/components/u-form-item/u-form-item.vue";
import UTag from "../../../../uview-ui/components/u-tag/u-tag.vue";
import USticky from "../../../../uview-ui/components/u-sticky/u-sticky.vue";
import UniDataSelect from "../../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import UDropdown from "../../../../uview-ui/components/u-dropdown/u-dropdown.vue";
import UCalendar from "../../../../uview-ui/components/u-calendar/u-calendar.vue";
import UButton from "../../../../uview-ui/components/u-button/u-button.vue";

export default {
  components: {
    UButton,
    UCalendar,
    UDropdown,
    UniDataSelect,
    USticky, UTag, UFormItem, UForm, UInput, UModal, UCol, URow, UCell, ULoadingIcon, UList, UListItem},
  data() {
    return {
      initFlag: false,
      DateShow: false,
      DateMmode: 'single',
      loading: false,
      show: false,
      confirmDisabled: true,
      focusFlag: true,
      title: '',
      formType: 1,
      formTypeInfo : [
        {
          value: 1,
          text: '扫码',
        },
        {
          value: 2,
          text: '订单',
        },
        {
          value: 3,
          text: '物料',
        },
        {
          value: 4,
          text: '供应商',
        },
      ],
      options: [],
      items: [],
      listKey: Date.now(),
      tempItem: null,
      total: 0,
      form: {},
      param: {
        pageNum: 0,
        pageSize: 5,
        formType: null,
        searchKey: null,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
      },
    }
  },
  onLoad() {
    this.items = [];
    this.loadMore();
    try {
      this.initScan();
      this.initFlag = true;
    } catch (e) {
      this.$modal.showToast('该类型设备暂不支持红外扫码', e)
    }
  },
  beforeDestroy() {
    if (this.initFlag) {
      let globalEvent = uni.requireNativePlugin('globalEvent');
      globalEvent.removeEventListener('iDataBarcodeEvent', this.handlePdaScan);
    }
  },
  methods: {
    initScan() {
      let barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
      barcodeModel.initScan((ret) => {
        if (ret.code === 'success') {
          console.log("初始化成功");
        }
      });
      barcodeModel.setOutputMode(4,(ret) => {
        if (ret.code === 'success') {
          console.log("模式设置成功");
        }
      });
      let globalEvent = uni.requireNativePlugin('globalEvent');
      let that = this;
      this.handlePdaScan = function(res) {
        that.checkSearchKey(res.barcode);
      }
      globalEvent.addEventListener('iDataBarcodeEvent', this.handlePdaScan);
    },
    checkSearchKey(result) {
      if (result === null || result === '' || result.length < 11 || !result.toUpperCase().includes("ALL")) {
        this.$modal.showToast( '请扫描正确的条码:' + result)
        return;
      }
      let datas = result.split("#");
      if (datas.length === 7 && result.toUpperCase().includes("ALL")) {
        this.formType = 1;
        this.param.searchKey = result;
        this.resetParam();
        this.param.formType = 1;
        this.param.invCode = datas[0];
        this.param.orderNo = datas[3];
        this.param.pageNum = 0;
        this.items = [];
        this.loadMore();
      } else {
        this.$modal.showToast('扫码失败, 请扫描正确的条码' + result)
      }

    },
    loadMore() {
      this.loading = true;
      this.param.pageNum = this.param.pageNum + 1;
      stockTaskList(this.param).then(res => {
        this.listKey = Date.now();
        this.total = res.total;
        if (res.rows.length > 0) {
          res.rows.forEach(item => this.items.push(item));
        } else {
          this.$modal.msg("没有上架任务！");
        }
        this.loading = false;
      });
    },
    confirmDate(e) {
      this.form.productionDate = e[0];
      this.DateShow = false;
    },
    resetData(row) {
      this.form = {
        id  : row.id,
        actQty  : (row.qty - row.inQtySum),
        actasnLoc_code  : row.actasnLoc_code,
        batchNo :  row.batchNo,
        isBatch : row.isBatch,
        isEffective :  row.isEffective,
        productionDate  : row.productionDate,
        business  : row.business,
        company :  row.company,
        employee  : row.employee,
        inQtySum  : row.inQtySum,
        inventory :  row.inventory,
        isSerialNo  : row.isSerialNo,
        pda : row.pda,
        porderDetailId  : row.porderDetailId,
        porderMainId  : row.porderMainId,
        porderNo: row.porderNo,
        qty: row.qty,
        stockinLoc: row.stockinLoc,
        stockinLoc_code: row.stockinLoc_code,
        stockinLoc_name: row.stockinLoc_name,
        warehouse: row.warehouse,
        stockinNo: row.stockinNo,
        invCode: row.invCode,
        invName: row.invName,
        invSpec: row.invSpec,
        orderNo: row.orderNo,
        suppLierName: row.suppLierName,
        whName: row.whName,
        unitName: row.unitName,
        businessName: row.businessName,
        pageSize: row.pageSize,
        pageNum: row.pageNum,
        carrier: row.carrier
      }
    },
    handleSubmit(row) {
      this.resetData(row);
      this.tempItem = row;
      this.show = true;
    },
    cancelForm() {
      this.show = false;
    },
    submitForm() {
      if (parseFloat(this.form.actQty) === 0) {
        this.$modal.showToast("提交不能为0！");
        this.confirmDisabled = true;
        return;
      }
      if (this.form.isBatch === 1 && (this.form.batchNo === '' || this.form.batchNo === null)) {
        this.$modal.showToast("请输入批次号！");
        this.confirmDisabled = true;
        return;
      }
      if (this.form.isEffective === 1 && (this.form.productionDate === '' || this.form.productionDate === null)) {
        this.$modal.showToast("请输入生产日期！");
        this.confirmDisabled = true;
        return;
      }
      this.confirmDisabled = false;
      commitStockInPDA(this.form).then(() => {
        let index = this.items.indexOf(this.tempItem);
        if (index > -1) {
          this.items.splice(index, 1);
        }
        this.$modal.msgSuccess("上架成功！");
        this.items = [];
        this.param.pageNum = 0;
        this.loadMore();
        this.show = false;
        this.confirmDisabled = true;
      }).catch((error) => {
        this.$modal.msgError(error);
        this.confirmDisabled = true;
      });
    },
    scrollTolower() {
      if (this.items.length >= this.total) {
        this.$modal.showToast("没有更多数据了");
        return;
      }
      // 计算最大页数
      let maxPage = Math.ceil(this.total / this.param.pageSize);
      if (maxPage === this.param.pageNum) {
        this.$modal.showToast("已到最后一页");
        return;
      }
      this.loadMore()
    },
    resetParam() {
      this.param = {
        pageNum: 0,
        pageSize: 10,
        invCode: null,
        batchNo: null,
        suppLierName: null,
        orderNo: null,
        formType: this.param.formType,
        searchKey: this.param.searchKey,
      }
    },
    searchList(searchKey) {
      if (searchKey === null || searchKey === '') {
        return;
      }
      this.resetParam();
      this.items = [];
      let searchFlag = false;
      this.param.formType = this.formType;
      if (this.param.formType === 1 && searchKey.length >= 11 && searchKey.toUpperCase().includes("ALL")) {
        // 扫码搜索
        let datas = searchKey.split("#");
        searchFlag = true;
        this.param.invCode = datas[0];
        this.param.orderNo = datas[3];
      } else if (this.param.formType === 2 && this.param.searchKey.length > 1) {
        // 订单号搜索
        searchFlag = true;
        this.param.orderNo = searchKey;
      } else if (this.param.formType === 3 && this.param.searchKey.length > 1) {
        // 物料搜索
        searchFlag = true;
        this.param.invCode = searchKey;
      } else if (this.param.formType === 4 && this.param.searchKey.length > 1) {
        // 供应商搜索
        searchFlag = true;
        this.param.suppLierName = searchKey;
      }
      if (searchFlag) {
        this.param.pageNum = 0;
        this.loadMore();
      }
    },
  }

}
</script>
<style>
.custom-list-item {
  background-color: #ADD8E6;

  /* 如果需要让整个列表项点击区域都生效，可能还需要下面这行 */
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
  height: 100%; /* 根据实际情况调整高度 */
}
</style>
